package com.kevin.netty.server.handler;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.LastHttpContent;

public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

	private URL baseUrl = HttpHandler.class
									 .getProtectionDomain()
									 .getCodeSource()
									 .getLocation();
	
	// 定义文件的根目录
	private final String WEB_ROOT = "webroot";
	
	// 根据文件名称获取指定文件
	private File getFileFromRoot(String fileName) throws URISyntaxException{
		String path = baseUrl.toURI() + WEB_ROOT + "/" + fileName;
		path = !path.startsWith("file:") ? path : path.substring(5);
		path = path.replaceAll("//", "/");
		return new File(path);
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
		// 获取用户请求的uri
		String uri = request.uri();
		
		String page = uri.equals("/")?"chat/html" : uri;
		
		RandomAccessFile file = null;
		try{
			file = new RandomAccessFile(getFileFromRoot(page), "r");
			
		}catch(Exception e){
			ctx.fireChannelRead(request.retain());
		}
		
		String contentType = "text/html";
		 
		if(uri.endsWith(".css")){
			contentType = "text/css;";
		}else if(uri.equals(".js")){
			contentType = "text/javascript;";
		}else if(uri.toLowerCase().matches("(jpg|png|gif)$")){
			String ext = uri.substring(uri.lastIndexOf("."));
			contentType = "image/"+ext+";";
		}
		
		HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
		
		response.headers().set(HttpHeaders.Names.CONTENT_TYPE,contentType+"charset=utf-8;");
		
		boolean keepAlive = HttpUtil.isKeepAlive(request);
		if(keepAlive){
			response.headers()
					.set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
					.set(HttpHeaders.Names.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		}
		
		ctx.write(response);
		
		ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
		// 清空缓冲区
		ChannelFuture f = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
	
		if(!keepAlive){
			f.addListener(ChannelFutureListener.CLOSE);
		}
		
		file.close();
	
	}

	

}
